{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "645c9c82-ae55-48cc-ac7c-d407d611bfcc",
   "metadata": {},
   "outputs": [
    {
     "ename": "IndentationError",
     "evalue": "unindent does not match any outer indentation level (<string>, line 13)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m<string>:13\u001b[1;36m\u001b[0m\n\u001b[1;33m    wordsList.extend(line)\u001b[0m\n\u001b[1;37m                          ^\u001b[0m\n\u001b[1;31mIndentationError\u001b[0m\u001b[1;31m:\u001b[0m unindent does not match any outer indentation level\n"
     ]
    }
   ],
   "source": [
    "from jieba import cut\t#导入中文分词库\n",
    "from re import sub\n",
    "#定义getWords()函数，用于提取指定文件（邮件文件）中的词语\n",
    "def getWords(file,stopList):\n",
    "    wordsList=[]\n",
    "    for line in open(file,encoding='utf-8'):\n",
    "         line=line.strip()\n",
    "        #过滤干扰字符或无效字符\n",
    "         line=sub(r'[.【】0-9、——，。！\\~*]','',line)  \n",
    "         line=cut(line)\n",
    "        #过滤长度为1的单个字\n",
    "         line=filter(lambda word:len(word)>1,line) \n",
    "        wordsList.extend(line)\n",
    "        #过滤停用词，剩余有效词语\n",
    "        words=[]\n",
    "        for i in wordsList:\n",
    "            if i not in stopList and i.strip()!='' and i!=None:\n",
    "               words.append(i)\n",
    "    return words\n",
    "from collections import Counter\n",
    "from itertools import chain\n",
    "#提取训练集所有文件中的词语\n",
    "allwords=[]\n",
    "for spamfile in spamFileList:\n",
    "words=getWords(\"../item5/item5-ss-data/spam/\"+spamfile,stopList)\n",
    "allwords.append(words)\n",
    "for normalfile in normalFileList:\n",
    "words=getWords(\"../item5/item5-ss-data/normal/\"+normalfile,stopList)\n",
    "allwords.append(words)\n",
    "print(\"训练集中所有的有效词语列表：\")\n",
    "print(allwords)\n",
    "#提取训练集中出现频次最高的前10个词语\n",
    "frep=Counter(chain(*allwords))\t                  #获取有效词语出现的频次\n",
    "topTen=frep.most_common(10)\t\t#获取出现频次最高的前10个词语和对应的频次\n",
    "topWords=[w[0] for w in topTen]\t#获取出现频次最高的前10个词语\n",
    "print(\"训练集中出现频次最高的前10个词语:\")\n",
    "print(topWords)\n",
    "import numpy as np\n",
    "vector=[]\n",
    "for words in allwords:\n",
    "    temp=list(map(lambda x:words.count(x),topWords))\t\t\t                   #每个高频词语在每封邮件中出现的次数\n",
    "    vector.append(temp)\n",
    "vector=np.array(vector)\n",
    "print(\"10个高频词语在每封邮件中出现的次数：\")\n",
    "print(vector)\n",
    "from sklearn.naive_bayes import MultinomialNB\n",
    "terget=np.array([1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,])\n",
    "x,y=vector,target\n",
    "model=MultinomialNB()\n",
    "model.fit(x,y)\n",
    "test=os.listdir(\"../item5/item5-ss-data/test\")\n",
    "for testFile in test:\n",
    "    wirds=getWords(\"../item5/item5-ss-data/test/\"+testFile,stopList)\n",
    "    test_x=np.array(tuple(map(lambda x:words.count(x),topWords)))\n",
    "    result=model.predict(test_x.reshape(1,-1))\n",
    "    if result==1:\n",
    "        print('\"'+testFile+'\"'+\"是垃圾邮件\")\n",
    "    else:\n",
    "        print('\"'+testFile+'\"'+\"是正常邮件\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0f092a0-73d7-4640-9d30-71977f88e666",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
